from flask import Flask, request

app = Flask(__name__)

# 分别对高一 高二 高三 教室设置记录的文件
fs = [open("./高一.csv", "w"), open("./高二.csv", "w"), open("./高三.csv", "w")]
for f in fs:
    f.write("时间,分贝值\n")


@app.route('/')
def api():
    name = request.args.get('name')  # 获取采集点的信息（高一、高二、高三）
    time_ = request.args.get('time')  # 获取数据采集的时间
    data = request.args.get('data')  # 获取分贝值

    if name and time_ and data:  # 三者均不为空
        try:
            print(name, time_, data)
            fs[{"高一": 0, "高二": 1, "高三": 2}.get(name)].write(f"{time_},{data}\n")
            fs[{"高一": 0, "高二": 1, "高三": 2}.get(name)].flush()  # 立刻写出
        except BaseException as e:
            return {"code": -1, "msg": "出现了错误，错误原因：" + str(e)}
        return {"code": 0, "msg": "成功"}

    return {"code": -1, "msg": "提供数据出错"}


if __name__ == '__main__':
    app.run()

